#   Copyright (c) 2008 ToI-Planning <office@toi-planning.net>
# 
#   Redistribution and use in source and binary forms, with or without
#   modification, are permitted provided that the following conditions
#   are met:
# 
#   1. Redistributions of source code must retain the above copyright
#      notice, this list of conditions and the following disclaimer.
#
#   2. Redistributions in binary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#
#   3. Neither the name of the authors nor the names of its contributors
#      may be used to endorse or promote products derived from this
#      software without specific prior written permission.
#
#   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
#   TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
#   PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
#   LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
#   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
#   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
#  $Id: App.pm 38 2008-10-22 13:52:43Z usualoma $

package TinyMCE::App;
use strict;
use File::Basename;

sub plugin_data_post_save {
	my ($cb, $obj, $original) = @_;
	my $plugin = MT->component('TinyMCE');
	my $app = MT->instance;

	if (lc($app->param('plugin_sig')) ne $plugin->id) {
		return;
	}

	require MT::Blog;
	my $blog_id = $app->param('blog_id') || 0;

	my @ids = $app->param('tiny_mce_field_ids');
	$plugin->set_config_value(
		'tiny_mce_fields', \@ids, $blog_id ? ('blog:' . $blog_id) : undef
	);
}

sub param_edit_entry {
	my ($cb, $app, $param, $tmpl) = @_;
	my $plugin = $app->component('TinyMCE');

	my $hash = $plugin->get_config_hash('system') || {};

	my $static_url = $app->config('StaticWebPath');
	$static_url =~ s/\/?$//;

	my $buttons = '';
	if ($hash->{'theme_advanced_buttons_set'} eq 'custom') {
		$buttons = <<__EOH__;
		param['theme_advanced_buttons1'] =
			'@{[ $hash->{'theme_advanced_buttons1'} ]}';
		param['theme_advanced_buttons2'] =
			'@{[ $hash->{'theme_advanced_buttons2'} ]}';
		param['theme_advanced_buttons3'] =
			'@{[ $hash->{'theme_advanced_buttons3'} ]}';
		param['theme_advanced_buttons4'] =
			'@{[ $hash->{'theme_advanced_buttons4'} ]}';
		param['theme_advanced_buttons5'] =
			'@{[ $hash->{'theme_advanced_buttons5'} ]}';
__EOH__
	}
	elsif ($hash->{'theme_advanced_buttons_set'} eq 'full') {
		my $hash = $plugin->get_config_hash('blog:0');
		for (my $i = 1; $i <= 5; $i++) {
			my $key = 'theme_advanced_buttons' . $i;
			$buttons .= "param['$key'] = '" . $hash->{$key} . "';\n";
		}
	}
	elsif ($hash->{'theme_advanced_buttons_set'} eq 'table') {
		$buttons = <<__EOH__;
		param['theme_advanced_buttons1'] = 'bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,forecolor,backcolor,|,fontselect,fontsizeselect';
		param['theme_advanced_buttons2'] = 'undo,redo,|,link,unlink,|,hr,removeformat,|,mt_insert_image,mt_insert_file,|,tablecontrols';
		param['theme_advanced_buttons3'] = '';
		param['theme_advanced_buttons4'] = '';
		param['theme_advanced_buttons5'] = '';

		param['theme_advanced_fonts'] = 'serif=serif;sans-serif=sans-serif;monospace=monospace';
		param['plugins'] = 'movabletype,table';
__EOH__
	}
	else {
		$buttons = <<__EOH__;
		param['theme_advanced_buttons1'] = 'bold,italic,underline,strikethrough,|,forecolor,backcolor,|,fontselect,fontsizeselect';
		param['theme_advanced_buttons2'] = 'justifyleft,justifycenter,justifyright,justifyfull,|,bullist,numlist,|,outdent,indent,|,undo,redo,|,link,unlink,|,hr,removeformat,|,mt_insert_image,mt_insert_file';
		param['theme_advanced_buttons3'] = '';
		param['theme_advanced_buttons4'] = '';
		param['theme_advanced_buttons5'] = '';

		param['theme_advanced_fonts'] = 'serif=serif;sans-serif=sans-serif;monospace=monospace';
		param['plugins'] = 'movabletype';
__EOH__
	}

	my $font_settings = '';
	if ($hash->{'theme_advanced_font_setting'} eq 'custom') {
        my $fonts = $hash->{'theme_advanced_fonts'};
        $fonts = join(';', grep(!/^\s*$/, split(/;?\s*(\n|\r)/, $fonts)));
		$font_settings = <<__EOH__;
        param['theme_advanced_font_sizes'] =
			'@{[ $hash->{'theme_advanced_font_sizes'} ]}';
        param['theme_advanced_fonts'] = '$fonts';
__EOH__
	}

	my $css_settings = '';
	if ($hash->{'theme_content_css_type'} eq 'url') {
		$css_settings = <<__EOH__;
        param['content_css'] = '@{[ $hash->{'theme_content_css_type'} ]}';
__EOH__
	}
	elsif ($hash->{'theme_content_css_type'} eq 'content') {
		my $uri = $app->app_uri . '?__mode=tiny_mce_content_css';
		$css_settings = <<__EOH__;
        param['content_css'] = '$uri';
__EOH__
	}

	my $other_config = '';
	if (
		($hash->{'tiny_mce_config_type'} eq 'custom')
		&& (my $v = $hash->{'tiny_mce_config_value'})
	) {
		$other_config = <<__EOH__;
(function() {
	var hash = $v;
	for (k in hash) {
		param[k] = hash[k];
	}
})();
__EOH__
	}

	my $lang = $app->user->preferred_language;
	$param->{'js_include'} ||= '';
	$param->{'js_include'} .= <<__EOH__;
<script type="text/javascript" src="$static_url/plugins/TinyMCE/lib/jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript" src="$static_url/plugins/TinyMCE/js/initialize.js"></script>
<script type="text/javascript">
(function() {
	var languages = {
		'ja': 'ja',
		'en-us': 'en',
		placement: null
	};
	var original = tinyMCE.init;
	tinyMCE.init = function(param) {
		$buttons
		$font_settings
		$css_settings
		$other_config
		param['language'] = languages['$lang'] || 'en';
		original.apply(tinyMCE, [param]);
	};
})();
</script>
__EOH__
}

sub source_edit_entry {
	my ($cb, $app, $tmpl) = @_;
	my $plugin = MT->component('TinyMCE');
	my $blog_id = $app->param('blog_id') or return;
	my @ids = ();

	my $system_hash = $plugin->get_config_hash() || {};
	my $hash = $plugin->get_config_hash('blog:' . $blog_id) || {};

	if ($hash->{'tiny_mce_for_excerpt'}) {
		push(@ids, 'excerpt');
	}

    eval { require CustomFields::Field; };
    if (! $@) {
		my @field_ids = (
			@{ $hash->{'tiny_mce_fields'} || [] },
			@{ $system_hash->{'tiny_mce_fields'} || [] }
		);
		my @fields = CustomFields::Field->load({
			'blog_id' => [ 0, $blog_id ],
			'obj_type' => $app->param('_type'),
			'type' => 'textarea',
			'id' => \@field_ids,
		});
		foreach my $f (@fields) {
			push(@ids, 'customfield_' . $f->basename);
		}
	}

	if (@ids) {
		my $ids = join(',', @ids);
		my $script = <<__EOH__;
<script type="text/javascript">
(function() {

	function insertHTML(html, field) {
		if (field) {
			field = field.replace('___tinymcefield___', 'customfield');
		}
		/* At this context field is not ignored. we have a few editor */
		if (
			(! field)
			|| (field == 'editor-content-textarea')
			|| ((! tinyMCE) || (! tinyMCE.get(field)))
		) {
			this.fixHTML( this.editor.insertHTML( html ) );
		}
		else {
			var ed = tinyMCE.get(field);
			ed.focus();
			ed.selection.moveToBookmark(
				ed.movabletype_plugin_bookmark
			);
			ed.execCommand('mceInsertContent', false, html);
		}
	}

	App.singletonConstructor =
	MT.App = new Class( MT.App, {
		insertHTML: insertHTML,
		placement: null
	} );
	if (window.app) {
		window.app.insertHTML = insertHTML;
	}

	tinyMCE.init({
		elements: '$ids'
	});
})();
</script>
__EOH__

		#$$tmpl .= $script;
		my $replace = '<mt:?include[^>]*name="include/footer.tmpl"[^>]*>';
		$$tmpl =~ s#$replace#$script$&#i;
	}

}

sub init_request {
	my ($app) = @_;
	my $plugin = MT->component('TinyMCE');
	
	return if !($app->can('param')); # God knows where we'll be coming from!

	my $blog_id = $app->param('blog_id') or return;

	if ($plugin->get_config_value('tiny_mce_for_body', 'blog:' . $blog_id)) {
		$app->config('RichTextEditor', 'TinyMCE');

		$plugin->{registry}->{richtext_editors}->{archetype} =
			$plugin->{registry}->{richtext_editors}->{tinymce};
	}
}

sub content_css {
    my $app = shift;
	my $plugin = $app->component('TinyMCE');

	$app->{cgi_headers}{'Content-Type'} = 'text/css; charset=UTF-8';
	$plugin->get_config_value('theme_content_css_content');
}

1;
